<template>
    <div class="callLogs">
        <wtop></wtop>
        <div class="center">
            <div class="right">
                <div style="height: 16px; width: 100%; background: #EFEFEF;"></div>
                <div class="powertop">
                  <router-link class="powertopli" to="/callsystem/orderCallLogs">订单外呼</router-link>
                  <router-link class="powertopli powertopact" to="/callsystem/callLogs">其它</router-link>
                </div>
                <div class="conlist" v-loading='loading'>
                    <div class="flex">
                        <div class="gong gl">
                          <el-form :inline="true" :model="formInline">
                            <el-form-item label="任务名称：">
                              <el-input v-model="formInline.name" placeholder="任务名称"></el-input>
                            </el-form-item>
                            <el-form-item label="业务ID：">
                              <el-input v-model="formInline.number" placeholder="业务ID"></el-input>
                            </el-form-item>
                            <!-- <el-form-item label="用户号码：">
                              <el-input v-model="formInline.mobile" placeholder="用户号码"></el-input>
                            </el-form-item> -->
                              <el-form-item label="意向标签：">
                            <el-select clearable v-model="formInline.tag" placeholder="请选择">
                             <el-option
                               v-for="(item,index) in tagList"
                               :key="index"
                               :label="item.name"
                               :value="item.id">
                             </el-option>
                            </el-select>
                            </el-form-item>
                            <el-form-item label="拨通状态:">
                              <el-select v-model="formInline.called_status  " clearable placeholder="拨通状态">
                                <el-option label="未拨通" value="1">未拨通</el-option>
                                <el-option label="已拨通" value="2">已拨通</el-option>
                              </el-select>
                            </el-form-item>
                            <el-form-item>
                            <el-button type="danger" @click="search">检索</el-button>
                            <el-button type="text" @click="downloadTask">导出拨打记录</el-button>
                            </el-form-item>
                            </el-form>
                        </div>
                    </div>
                    <div class="list">
                        <div class="th">业务ID</div>
                        <div class="th">联系电话</div>
                        <div class="th">所属任务</div>
                        <div class="th">任务类型</div>
                        <div class="th">意向标签</div>
                        <div class="th">拨打次数</div>
                        <div class="th">最近一次通话时间</div>
                        <div class="th">最近一次通话时长</div>
                        <div class="th">外呼目标达成</div>
                        <div class="th td2">操作</div>
                    </div>
                    <div class="list" v-for="(item,index) in list" :key="index">
                        <div class="td">{{item.mission_id}}</div>
                        <div class="td">{{item.mobile}}</div>
                        <div class="td">{{item.task_name}}</div>
                        <div class="td">{{item.type_name}}</div>
                        <div class="td">{{item.tag_name}}</div>
                        <div class="td">{{item.times}}</div>
                        <div class="td">{{item.last_call_at}}</div>
                        <div class="td">{{item.last_time}}</div>
                        <div class="td">{{item.result}}</div>
                        <div class="td td2">
                          <img class="call-icon" src="../../../static/img/waihu_call.png" @click="startCall(item)">
                        </div>
                    </div>
                    <el-pagination background layout="total,prev, pager, next" :current-page="page" @current-change="fanye" :page-size="pagesize" :total="total"></el-pagination>
                </div>
            </div>
        </div>
        <el-dialog title="外呼拨打" :visible.sync="startcall" width="1000px" @close="callclosed" center :close-on-click-modal="false" :close-on-press-escape="false">
            <el-form :model="callform" ref="callform" @submit.native.prevent label-width="100px">
              <div class="formflex">
                <el-form-item label="业务ID：">
                  <div class="valwidth">{{callform.mission_id}}</div>
                </el-form-item>
                <div class="lineflex">
                  <el-form-item label="意向标签：">
                    <div class="intention">{{want_text}}</div>
                  </el-form-item>
                </div>
              </div>
              <div class="formflex">
                <el-form-item label="用户姓名：">
                  <div class="">{{callform.user_name}}</div>
                </el-form-item>
              </div>
              <div class="formflex">
                <el-form-item label="当前拨号：">
                  <div class="mobile" v-if="changeM">{{callform.mobile}}</div>
                  <el-input ref="mobile" v-if="!changeM" v-model="callform.mobile" clearable></el-input>
                </el-form-item>
                <div class="callbtn">
                  <el-button type="text" v-if="changeM" @click="changeMobile" style="margin-left: 10px;">修改号码</el-button>
                  <el-button type="primary" v-if="!changeM" @click="saveMobile" style="margin-left: 10px;">保存</el-button>
                  <el-button type="danger" icon="el-icon-phone-outline" :disabled="cancall" :loading="canCall" @click="call">拨号</el-button>
                </div>
              </div>
              <div class="formflex">
                <el-form-item label="用户信息：">
                  <div class="intention">{{callform.user_info}}</div>
                </el-form-item>
              </div>
              <div class="formflex">
                <el-form-item label="产品名：">
                  <div class="intention">{{callform.product}}</div>
                </el-form-item>
              </div>
              <div class="formflex">
                <el-form-item label="地址：">
                  <div class="intention">{{callform.address}}</div>
                </el-form-item>
              </div>
              <div class="formflex">
                <el-form-item label="备注信息：">
                  <div class="remarkBox">
                    <el-form-item v-if="remark1" label="备注1：">
                      <div class="intention">{{callform.remark_one}}</div>
                    </el-form-item>
                    <el-form-item v-if="remark2" label="备注2：">
                      <div class="intention">{{callform.remark_two}}</div>
                    </el-form-item>
                    <el-form-item v-if="remark3" label="备注3：">
                      <div class="intention">{{callform.remark_three}}</div>
                    </el-form-item>
                  </div>
                </el-form-item>
              </div>
              <div class="formflex">
                <el-form-item label="话术要求：">
                  <div class="intention">{{demand}}</div>
                </el-form-item>
              </div>
              <div class="formflex col">
                <div style="font-weight: bold;">历史外呼记录：</div>
                <div class="logs">
                  <div class="log">
                    <div class="ls">
                    <div class="list" v-for="(item,index) in logs" :key="index">
                      <div class="">{{item.created_at}}</div>
                      <div class="status" :class="item.called == '已接通' ? 'sucess' : item.called == '未接通' ? 'error' : ''">{{item.called}}</div>
                      <div class="time" :class="item.called == '已接通' ? 'sucess' : item.called == '未接通' ? 'error' : ''">时长：{{item.time}}</div>
                      <!-- <div class="outperson">外呼人：{{XXXXX}}</div> -->
                      <div class="remark">备注：{{item.remark}}</div>
                      <div class="audioplay" v-if="item.record">
                      	<audio class="audio" controls>
                          <source :src="item.record" type="audio/mpeg">
                      		<!-- <source :src="'/storage/upload/record/'+item.record" type="audio/mpeg"> -->
                      		您的浏览器不支持 audio 元素。
                      	</audio>
                      </div>
                    </div>
                  </div>

                  </div>
                </div>
              </div>
                <el-form-item label="意向标签：" class="listtag">
                  <el-button v-for="(item,index) in tagList" :key="index" :type="callform.tag == item.id ? 'danger' : 'info'" @click="wantswitch(item)">{{item.name}}</el-button>
                  <el-button type="text" v-if="!showTagValue" @click="addTag">+新建标签</el-button>
                  <div v-if="showTagValue" style="display: inline-flex;">
                    <el-input ref="tagValue" v-model="addTagValue"></el-input>
                    <el-button type="primary" @click="saveTagValue" style="margin-left: 10px;">保存</el-button>
                  </div>
                </el-form-item>
                <el-form-item label="拨打备注：" class="listtag">
                  <el-input type="textarea" :rows="3" v-model="callform.remark"></el-input>
                </el-form-item>
                <div class="formflex formsubmit">
                  <el-button type="danger" @click="noPass">标记未接通</el-button>
                  <el-button type="success" @click="sendForm('callform')">标记已接通</el-button>
                  <!-- <div class="collection" v-if="collect===1"><i class="el-icon-star-off"></i>添加收藏</div>
                  <div class="collection" v-if="collect===0"><i class="el-icon-star-on"></i>已收藏</div> -->
                </div>
            </el-form>

        </el-dialog>
        <wfoot></wfoot>
    </div>

</template>

<script>
    import axios from 'axios'
    import wtop from '@/components/callsystem/wtop.vue'
    import wfoot from '@/components/callsystem/wfoot.vue'
    import moment from "moment";

    export default {
        components: {
            "wtop": wtop,
            "wfoot": wfoot,
        },
        name: "callLogs",
        data() {
            return {
              srclogo:"./static/img/wh_icon1.png",
              setParams: {
                ip: '',
                port: 1818,
                line: 1,
              },
                formInline:{
                  name: '',
                  number: '',
                  mobile: '',
                  tag: '',
                  called_status: ''
                },
                total:0,
                pagesize:20,
                page:1,
                list:[],
                loading:false,
                startcall: false,
                callform: {
                  id: '',
                  mobile: '',
                  tag: 0,
                  user_info: '',
                  remark: ''
                },
                noCall: false,
                cancall: false,
                canCall: false,
                nopass: 2, //已接通
                logs: [],
                want_text: '',

                changeM: true, // 修改号码
                remark1: false,
                remark2: false,
                remark3: false,
                tagList: [],
                showTagValue: false,
                addTagValue: '',
                demand: '',
                url: ''
            }
        },
        created() {
          this.url = window.location.origin
          if(JSON.parse(localStorage.getItem('CALL_OUT'))){
            var setParams = JSON.parse(localStorage.getItem('CALL_OUT'))
          }
          // console.log(setParams);
          this.getUserIP((ip) => {
            this.setParams.ip = ip;
            if(!ip){
              this.setParams.ip = setParams.ip
            }
          });
          this.getlist()
          this.moretagList()
        },
        mounted() {

        },
        methods: {
          //导出
          downloadTask(){
            var a = document.createElement("a");
            a.setAttribute("href", this.url+`/api/plan-market/my/call/details/export?task_name=${this.formInline.name}&mission_id=${this.formInline.number}&tag=${this.formInline.tag}&called_status=${this.formInline.called_status}`);
            a.click();
          },
          //新建标签
          addTag(){
            this.showTagValue = true
            this.$nextTick(_ => {
              this.$refs.tagValue.$refs.input.focus()
            })
          },
          saveTagValue(){
            var that = this
            axios.post("/api/plan-market/call/task/tag", {name:this.addTagValue})
              .then(function(response) {
                  if (response.data.msg.code == 0) {
                      that.showTagValue = false
                      that.addTagValue = ''
                      that.moretagList()
                  }else{
                      that.$message.error(response.data.msg.info);
                  }
              })
          },
          //意向标签
          moretagList(){
            var that = this
            axios.get("/api/plan-market/call/tag/list")
              .then(function(response) {
                  if (response.data.msg.code == 0) {
                    that.tagList = response.data.data
                  }else{
                      that.$message.error(response.data.msg.info);
                  }
              })
          },
          //修改号码
          changeMobile(){
            this.changeM = false
            this.cancall = true
            this.$nextTick(_ => {
              this.$refs.mobile.$refs.input.focus()
            })
          },
          saveMobile(){
            // if(!(/^1[3456789]\d{9}$/.test(this.callform.mobile))){
            //   this.$message.error('号码格式错误，请仔细检查~');
            //   return
            // }
            var that = this
            axios.post("/api/plan-market/call/detail/update", {id: this.callform.id,mobile:this.callform.mobile})
              .then(function(response) {
                  if (response.data.msg.code == 0) {
                      that.changeM = true
                      that.cancall = false
                  }else{
                      that.$message.error(response.data.msg.info);
                  }
              })
          },
          //websocket服务
          websocket() {
            var that = this
            if(typeof(WebSocket) === "undefined"){
                 this.$message.error("您的浏览器不支持socket")
            }else{
                // 实例化socket
                let ws_address = 'ws://' + this.setParams.ip + ':' + this.setParams.port
                var timestamp = new Date().getTime()
                var socket = new WebSocket(ws_address)
                socket.onopen = function(){
                  socket.send("line="+that.setParams.line+"number=STOPcallOutId="+timestamp*1000)
                }
            }
          },
          websocket1(number) {
            var that = this
            if(typeof(WebSocket) === "undefined"){
                 this.$message.error("您的浏览器不支持socket")
            }else{
                // 实例化socket
                let ws_address = 'ws://' + this.setParams.ip + ':' + this.setParams.port
                var timestamp = new Date().getTime()
                var socket = new WebSocket(ws_address)
                socket.onopen = function() {
                  socket.send("line="+that.setParams.line+"number="+number+"callOutId="+timestamp)
                  setTimeout(() => {
                    that.canCall = false
                    that.$message.success("外呼成功，请拿起电话~")
                  },1500)  //避免服务反应迟钝，延时一秒，可适当延长
                }
            }
          },
          getUserIP(onNewIP) {
              let MyPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
              let pc = new MyPeerConnection({
                  iceServers: []
                });
              let noop = () => {
                };
              let localIPs = {};
              let ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
              let iterateIP = (ip) => {
                if (!localIPs[ip]) onNewIP(ip);
                localIPs[ip] = true;
              };
              pc.createDataChannel('');
              pc.createOffer().then((sdp) => {
                sdp.sdp.split('\n').forEach(function (line) {
                  if (line.indexOf('candidate') < 0) return;
                  line.match(ipRegex).forEach(iterateIP);
                });
                pc.setLocalDescription(sdp, noop, noop);
              }).catch((reason) => {
              });
              pc.onicecandidate = (ice) => {
                if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
                ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
              };
          },
          callclosed(){
            this.canCall = false
            this.startcall = false
            this.changeM = true
            this.showTagValue = false
            this.want_text = ''
            this.getlist()
          },
          noPass(){
            this.nopass = 1
            // this.callform.tag = 0
            // this.callform.remark = ''
            this.sendForm('callform')
          },
          //拨打
          call(){
            var that = this
            this.canCall = true
            that.$message.warning("正在连接服务，请勿拿起电话~");
            axios.post("/api/plan-market/call/detail/can", {id: this.callform.id})
              .then(function(response) {
                  if (response.data.msg.code == 0) {
                    //创建两个socket
                    // that.websocket()
                    // setTimeout(()=>{
                      that.websocket1(that.callform.mobile)
                    // },2000)
                  }else{
                      that.$message.error(response.data.msg.info);
                  }
              })

          },
          //开始外呼
          startCall(item){
            this.startcall = true
            var that = this
            setTimeout(()=>{
              let audio = document.getElementsByClassName('audio');
              for(let i=0;i < audio.length-1;++i){
                audio[i].src = ''
              }
            },0)
			that.logs = ""
            axios.get("/api/plan-market/call/detail/info?id="+item.id)
            	.then(response => {
            		if(response.data.msg.code == 0){
                      if(response.data.data.detail){
                        that.moretagList()
                        that.callform = response.data.data.detail
                        that.demand = response.data.data.task.demand
                        for(var i in that.tagList){
                          if(that.callform.tag == that.tagList[i].id){
                            that.want_text = that.tagList[i].name
                          }
                        }
                        that.remark1 = that.callform.remark_one ? true : false
                        that.remark2 = that.callform.remark_two ? true : false
                        that.remark3 = that.callform.remark_three ? true : false
                        that.logs = response.data.data.logs
                        for (let i in that.logs) {
                        									that.logs[i].called = that.logs[i].called == 1 ? '未接通' : that.logs[i].called == 2 ? '已接通' : ''
                        if(that.logs[i].record){
                          if(that.logs[i].record.includes('https')){
                        
                          }else{
                            if(that.logs[i].record.includes('http')){
                              str.replace("http", "https")
                            }else{
                              that.logs[i].record = "https://call.91haoka.cn/" + that.logs[i].record
                            }
                          }
                        }
                              
                        								}
                      }else{
                        that.$message.success('任务外呼完毕，已经没有更多号码了^_^');
                        that.startcall = false
                      }
            		}else{
            			that.$message.error(response.data.msg.info);
            		}
            	})
          },
          //开始外呼窗口 意向切换
          wantswitch(item){
            this.callform.tag = item.id;
            this.want_text = item.name
          },
          sendForm(formName){
            this.canCall = false
            this.$refs[formName].resetFields();
            // let audio = document.getElementById('audio');
            // audio.pause()
            // audio.currentTime = 0;
            this.saveCall()
            // this.startCall()
          },
          //保存
          saveCall(){
            var that = this
            let data = {}
            data.id = this.callform.id
            data.tag = this.callform.tag
            data.remark = this.callform.remark
            data.called = this.nopass
            axios.post('/api/plan-market/task/detail/tag', data)
            	.then(response => {
            		if(response.data.msg.code == 0){
                  that.startcall = false
                  that.nopass = 2
                  that.$message.success('保存成功，继续加油哦~');
                  that.getlist()
            		}else{
            			that.$message.error(response.data.msg.info);
            		}
            	})
          },
            search:function(){
              // console.log(this.formInline);
              this.page = 1
                this.getlist()
            },
            //翻页
            fanye:function(page){
            	this.loading = true
            	this.page = page
            	this.getlist()
            },
            //获取列表
            getlist:function(){
                var that = this
                this.loading = true
                axios.get(`/api/plan-market/my/call/details?page=${this.page}&page_size=${this.pagesize}&task_name=${this.formInline.name}&mission_id=${this.formInline.number}&tag=${this.formInline.tag}&called_status=${this.formInline.called_status}`)
                	.then(response => {
                		if(response.data.msg.code == 0){
                            that.list = response.data.data.data
                            let resultArr = ['未达成','已达成']
                            for(let i in that.list){
                              that.list[i].result = resultArr[that.list[i].result]
                            }
                            that.total = response.data.data.total
                            that.loading = false
                		}else{
                			that.$message.error(response.data.msg.info);
                		}
                	})
            },
        }
    }
</script>

<style lang="scss" scoped>
    .callLogs{ margin: 0; padding: 0; background: #EFEFEF;
        .listupload{ font-size: 14px;
            .li{flex: 1; line-height: 38px; margin-top: 20px;}
            .el-button--primary{ background: #ffffff; color: #409EFF; border-color: #409EFF; }

        }
        .listtag{
          .el-form-item__label{font-weight: bold;}
          .el-button--danger{padding: 9px 30px!important;}
        }
        .center{ min-width: 1366px;width: 1366px; margin: 0 auto; display: flex; justify-content: space-between;
    		.right{ flex-basis: 1366px; background: #ECECEC;
              .title{border-bottom: 1px #EAEAEA solid;  line-height: 45px; padding-left: 30px; font-size: 16px; background: #F9F9F9; color: #727272}
              .topTag{display: flex;background: #fff;position: relative;border-bottom: #e2e0e3 1px solid;
                .topLogo{ font-size: 20px; color: #707070;display: flex;align-items: center;padding: 14px 0;
                  img{ width: 30px;height: 30px;margin: 0 10px;}
                }
              }
            }
            .powertop{ display: flex; width: 640px; }
            .powertopli{ cursor: pointer;flex-basis: 160px; line-height: 45px; border-top: 4px #EBECEF solid; color: #727272; border-right: 1px #EAEAEA solid; font-size: 14px; text-align: center;}
            .powertopact{ background: #FFFFFF; border-top: 4px #DD2727 solid;}
            .con{  background: #FFFFFF; padding: 30px 40px; display: flex; justify-content: space-between;
                .conleft{
                    .flex{ display: flex; margin-bottom: 20px;}
                    .gong{ margin-right: 30px; color: #333}
                }
                .conright{
                    .el-input__inner{ line-height: 40px !important; height: 40px !important;}
                }
            }
            .conlist{ padding: 30px; background: #FFFFFF;
                .flex{ display: flex; justify-content: space-between}
                .gong{ display: flex;
                    .el-date-editor.el-input{ width: 200px;}
                    .el-input__inner{ width: 250px;}
                    .el-button--danger{ margin-left: 20px;}
                    .el-button--primary{ padding: 10px 30px; background: #EEF7FF; border: 1px #EEF7FF solid; margin-left: 20px;}
                    .el-date-editor--month{ margin-right: 20px;}
                }
                .gl{ margin-bottom: 20px;
                    .el-input__inner{ width: 200px !important; }
                    .el-button--danger{ margin-left: 0px !important; margin-right: 20px;}
                }
                .ml{
                  .el-button--danger{ margin-left: 10px!important;}
                }
                .list{ display: flex; border-bottom: 1px #eaeaea solid;align-items: center;
                    .th{ background: #EAEAEA; text-align: center; flex: 1; padding: 15px 0; font-size: 14px;}
                    .td{ background: #ffffff; text-align: center; flex: 1; padding: 15px 0; font-size: 14px;}
                    .td2{
                      flex: 1.5;
                      .el-button{padding: 0;}
                      .call-icon{width: 22px;cursor: pointer;}
                    }
                }
                .el-pagination{ text-align: right; margin: 20px 0}
            }
    	}
      .formflex{display: flex;
        .mobile{color: #FB3535;font-size: 24px;}
        .valwidth{width: 150px;}
        .el-form-item__label{font-weight: bold;}
        .remarkBox{
          .el-form-item__label,.el-form-item__content{font-size: 14px;}
          .el-form-item__label{width: 60px!important;font-weight: normal;}
          .el-form-item__content{margin-left: 60px!important;}
        }
        .callbtn{
        .el-button--danger{padding: 14px 30px !important;margin-left: 20px;}

        }
        .intention{color: #727272;}
        .logs{
          width: 100%;margin: 10px 0;
          &:before,&:after{content: '';display: block;width: 100%;height: 1px;background: #D8D8D8;}
          .log{
            display: flex;justify-content: space-between;
          .ls{
            padding: 10px 0;width: 100%;font-size: 14px;
            .list{display: flex;justify-content: space-between;align-items: center;width: 100%;padding: 6px 0;
              .remark{width: 220px;height: 16px;overflow: hidden;}
            }
            .sucess{color: #51C93F;}
            .error{color:#D65757;}
          }
          .audioplay{
            .audio{
              height: 34px;
              &:focus {
                outline: -webkit-focus-ring-color auto 0px;
              }
            }
          }

          }
        }
        .el-input__inner{ width: 200px;}
        .lineflex{display: flex;
          .el-button--text{height: 40px;margin-left: 20px;}
        }

      }
      .el-button--info{background: #D9D9D9;border-color: #D9D9D9;padding: 9px 30px;
        &:hover{background: #D9D9D9;border-color: #D9D9D9;}
      }
      .col{flex-direction: column;margin-bottom: 22px;padding-left: 19px;}
      .formsubmit{justify-content: center;align-items: center;
        .el-button--danger{padding: 14px 30px !important;margin-left: 0;}
        .el-button--success{padding: 14px 30px !important;margin-left: 20px;margin-right: 20px;}
        .collection{
          display: flex;align-items: center;cursor: pointer;
          .el-icon-star-off{font-size: 16px}
          .el-icon-star-on{color: #FFAA00;font-size: 20px;}
        }
      }
    }
</style>
